package com.zhkj.lib.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.CallSuper
import androidx.fragment.app.Fragment
import com.zhkj.lib.utils.ToastUtil
import com.zhkj.lib.widget.LoadingStatuesDialog
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.disposables.Disposable

/**
 * Fragment基类，使用LifeCycle设置生命周期
 */
abstract class BaseFragment : Fragment(), BaseView {

    private var permissionDisposable: Disposable? = null
    private var hasLoad: Boolean = false
    var loadingStatusDialog: LoadingStatuesDialog? = null

    /**
     * 需要绑定的视图ID
     */
    abstract val layoutResId: Int

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(layoutResId, container, false)
    }

    @CallSuper
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        doBeforeInitUI()
        initUI()
    }

    override fun showLoadingView(content: String?) {
        if (loadingStatusDialog == null) loadingStatusDialog =
            LoadingStatuesDialog(BaseApplication.INSTANCE)
        if (loadingStatusDialog?.isShowing == false) loadingStatusDialog?.showLoading(content)
    }

    override fun hideLoadingView() {
        loadingStatusDialog?.dismiss()
    }

    override fun toast(content: String) {
        ToastUtil.show(content)
    }

    override fun requestPermission(permission: String, onGrant: () -> Unit, onDeny: () -> Unit) {
        if (RxPermissions(this).isGranted(permission)) {
            onGrant()
        } else permissionDisposable = RxPermissions(this).request(permission).subscribe {
            if (it) onGrant() else onDeny()
        }
    }

    @CallSuper
    override fun onResume() {
        super.onResume()
        if (!hasLoad) {
            initData()
            hasLoad = true
        }
    }

    /**
     * 初始化数据
     */
    open fun initData() = Unit

    /**
     * 在初始化视图之前的操作
     */
    open fun doBeforeInitUI() = Unit

    /**
     * 初始化UI
     */
    open fun initUI() = Unit

}